/**
 *权限管理 对应role.jsp
 */
define(["require","jquery", "public/app"],function (require,$, app) {

    function Role($container) {
        this._$container = $container;
        this._init();
    }

    Role.prototype._initUrlPath = function () {
        this.urlPaths = {
            roleData :app.urlBuild("/dirms/security/role/page"),
           // findRole :app.urlBuild("/dirms/security/role/findData/"),
            roleSave:app.urlBuild("/dirms/security/role/"),
            userSave:app.urlBuild("/dirms/security/user/"),
            userRoleData:app.urlBuild("/dirms/security/user/data/"),
            userData:app.urlBuild("/dirms/security/user/all"),
           // findUserByName:app.urlBuild("/dirms/security/user/query"),
            findUserDataByName:app.urlBuild("/dirms/security/user/userOfRole/"),
            roleTree:app.urlBuild("/dirms/security/authority/find"),
            roleAndAuthSave:app.urlBuild("/dirms/security/roleAndAuthority/")
        };
    };


    Role.prototype._init = function () {
        this._initUrlPath();
        var self = this;
        var dataReady = app.getDataReady();
         dataReady.pushDataSource({//逐个放入所有数据源
         url: this.urlPaths.roleData,
         key: 'roledata'
         });
       dataReady.pushDataSource({//逐个放入所有数据源
            url: this.urlPaths.userData,
            key: 'userData'
        });
        dataReady.once(
            function (readyData){
            self._initComponents(readyData);
        });
    };
    Role.prototype._initComponents = function(){
        //初始化控件
        this._initButton();
        this._initDataGrid();
        this._initTab();
        this._initEventBinding();
        this._initDialog();

    };

    //初始化按钮和文本框
    Role.prototype._initButton = function(){
        var self=this;
        $('#role_userAdd').linkbutton({
            iconCls:'icon-add',
            width:'10%',
            height:'30px',

            plain:true

        });
        $('#role_userDelete').linkbutton({
            iconCls:'icon-remove',
            width:'10%',
            height:'30px',
            plain:true
        });

        $('#role_find').searchbox({
            searcher:function(value){
                //通过角色名查找数据
                $('#role').datagrid('load',{name:value});
               /* $.ajax({
                    type:"GET",
                    url:self.urlPaths.findRole+value,
                    success:function(data){
                        if(data==""||data==null){alert(value+" 角色不存在");}
                        else{
                            $('#role_user').datagrid('loadData',data);
                            $('#role_finduser').searchbox('clear');
                        }
                    },
                    error:function(){alert("查询错误");}
                });*/
            },
            menu:'#role_search',
            prompt:'请输入关键字',
            iconCls:'icon_search',
            height:'30px'
        });
        $('#role_findres').searchbox({
            searcher:function(value){
                alert(value)
            },
            prompt:'请输入关键字',
            iconCls:'icon_search',
            height:'30px'
        });


        $('#role_finduser').searchbox({
            //用户数据查询
            searcher:function(value){
                if(value != "") {
                    var row = $('#role').datagrid('getSelected');
                    $.ajax({
                        type: "GET",
                        url: self.urlPaths.findUserDataByName + value + "/" + row.id,
                        success: function (data) {
                            if (data == "" || data == null) {
                                alert(value + " 用户不存在");
                            }
                            else {
                                $('#role_user').datagrid('loadData', data);
                                $('#role_finduser').searchbox('clear');
                            }
                        },
                        error: function () {
                            alert("查询错误");
                        }
                    });
                }
                else{
                    $('#role_user').datagrid('reload');
                }
            },
            prompt:'请输入用户名',
            iconCls:'icon_search',
            height:'30px'
        });
    };

    Role.prototype._initDialog = function(){
        var self = this;
        //添加角色对话框
        $("#roleDialog").dialog({
            title:'添加角色',
            closed:true,
            width:'auto',
            height:'auto',
            buttons:[
                {text:'提交',id:'addRole', iconCls:'icon-ok', handler:function() {
                    //提交保存新添加的角色
                    var roleData = $("#role_group").serializeJsonStr();
                        $.ajax({
                        url: self.urlPaths.roleSave,
                        type: "POST",
                        cache: false,
                        contentType: "application/json",
                        dataType: "json",
                        data: roleData,
                        success: function () {
                            $('#role').datagrid('reload', {
                                url: self.urlPaths.roleData
                            });
                            $('#roleDialog').dialog('close');
                            $.messager.alert('提示：', '添加成功');
                        }
                    });
                }},
                {text:'取消',iconCls:'icon-cancel',handler:function(){$('#roleDialog').dialog('close');}}
            ]
        });

        //添加新用户对话框
        $('#addUserDialog').dialog({
            closed:true,
            width:'auto',
            height:'auto',
            buttons:[
                {text:'提交',id:'saveUser', iconCls:'icon-ok',handler:function(){
                    //保存新添加的用户
                    var row = $('#role').datagrid('getSelected');
                   var userData = $("#role_addUser").serializeJsonStr();
                    $.ajax({
                        url:self.urlPaths.userSave,
                        type:"POST",
                        cache:false,
                        contentType: "application/json",
                        dataType: "json",
                        data : userData,
                        success: function(data){
                            //添加用户与角色的关联关系
                            $.ajax({
                                url:app.urlBuild("/dirms/security/userAndRole/"),
                                type:"POST",
                                cache:false,
                                contentType: "application/json",
                                async : false,
                                dataType: "json",
                                data : JSON.stringify({userId:data.id,roleId:row.id})
                            });
                            $('#role_user').datagrid('reload');
                            $('#addUserDialog').dialog('close');
                            $.messager.alert('提示：','添加成功');
                        },
                        error: function () {
                            $.messager.alert('提示','添加失败！','info');
                        }
                    });
                }},
                {text:'取消',iconCls:'icon-cancel', handler:function(){$('#addUserDialog').dialog('close');}}
            ],
            onLoad:function(){
                var row = $('#role').datagrid('getSelected');
                if(row != undefined&&row.length==1){
                $("#role_addUser").form("load",row);
            }
            }
        });
    };

    Role.prototype._initDataGrid =function(){
        var self= this;
        var on_off = false;//设置一个开关，防止tree数据加载时触发oncheck事情
        //初始化角色数据表格
        $('#role').datagrid({
            singleSelect: true,
            url:this.urlPaths.roleData,
            method:'get',
            height:'100%',
            width:'100%',
            //title:'角色名',
            columns:[[
                {field:'name',title:'角色名',width:'100%'}
            ]],
            toolbar: this._$container.find("#role_tloorbar"),
            onClickRow:function(){
                //单击角色表格中的某一行，加载对应行角色的基础属性
                var row = $('#role').datagrid('getSelected');
                $('#role_property').form('load',row);
                self._$container.find("#active").switchbutton(row.active ? "check" : "uncheck");
                $('#ofRole').textbox('setText',row.name);
                //单击角色表格中的某一行，加载对应行角色所拥有的用户
                $('#role_user').datagrid({
                    singleSelect: true,
                    rownumbers:true,
                    method:'get',
                    width: 'auto',
                    height: '100%',
                    pagination: true,
                    url: self.urlPaths.userRoleData+row.id,
                    columns: [[
                        {field:'name', title: '用户名', width: 150},
                        {field:'userName',title: '用户名称', width: 200}
                    ]],
                    toolbar: self._$container.find("#role_user_toolbar")
                });
                //获取当前角色所拥有的权限
                $.ajax({
                    type:'get',
                    url:app.urlBuild("/dirms/security/roleAndAuthority/data/"+row.id),
                //清空复选框
                    beforeSend:function(){
                        on_off = false;
                        var nodes = $('#role_function').tree('getChecked', 'checked');
                        $.each(nodes, function (index, item) {
                                    $('#role_function').tree('update',{
                                        target:item.target,
                                        checked:false
                                    })
                        });
                    },

                    //将当前所有节点的ID与该角色所拥有的菜单权限authorityId比对，若相等，则勾选上复选框
                    success:function(data){
                        var nodes = $('#role_function').tree('getChecked', 'unchecked');
                        $.each(nodes, function (index, item) {
                            if ($('#role_function').tree('isLeaf',item.target)) {
                                for(var i = 0;i<data.length; i++){
                                    if(item.id == data[i].authorityId){
                                        $('#role_function').tree('update',{
                                            target:item.target,
                                            checked:true
                                        })
                                    }
                                }
                           }
                        });
                        on_off = true;
                    }
                });
            }
        });

        //初始资源权限tab页
        $('#role_res').datagrid({
            singleSelect: true,
            pagination: true,
            url: '',
            method: 'get',
            width: 'auto',
            height: '100%',
           // idField:'id',
          //  treeField:'name',
          //  checkbox:true,
            columns: [[
                {field: 'resourceName', title: '资源名称', width: 200},
                {field: 'resourceType', title: '资源类型', width: 200},
                {field: 'permissionType', title: '权限类型', width: 200}
            ]],
            toolbar: this._$container.find("#role_res_toolbar")
        });

        //初始化功能权限TAB页
        $('#role_function').tree({
            url: this.urlPaths.roleTree,
            method: 'get',
            width: 'auto',
            height: '100%',
            checkbox:true,
            formatter: function (node) {
                return node.name;
            },
           loadFilter: function (data, parent) {//处理树节点状态。加载树的时候，根据子菜单数量决定书的状态，以便打开父节点时加载子节点
                $.each(data, function (index, item) {
                    item.state = item.childrenCount > 0 ? 'closed' : "open";
                });
                return data;
            },
            onCheck:function(node,checked){
                if(on_off){
                    //选中复选框分配权限
                    if(checked){
                        var rowa = $('#role').datagrid('getSelected');
                        if(rowa!=null){
                                    $.ajax({
                                        url: self.urlPaths.roleAndAuthSave,
                                        type: "POST",
                                        contentType: "application/json",
                                        dataType: "json",
                                        data: JSON.stringify({authorityId: node.id, roleId: rowa.id}),
                                        success:function(){$.messager.alert('提示：','分配成功');}
                                    });
                            }else{$.messager.alert('提示','请选择一个角色');}
                    }else{
                    //消掉复选框取消权限
                        var rowb = $('#role').datagrid('getSelected');
                            //获取该角色已拥有的权限
                                $.ajax({
                                    type:'get',
                                    url:app.urlBuild("/dirms/security/roleAndAuthority/data/"+rowb.id),
                                    success:function(data){
                                        for(var i = 0;i<data.length; i++){
                                            if(node.id == data[i].authorityId){
                                            //通过判断确定要取消的角色菜单权限的ID
                                                $.ajax({
                                                    type:'delete',
                                                    url:app.urlBuild("/dirms/security/roleAndAuthority/"+data[i].id),
                                                    success:function(){
                                                        $.messager.alert('提示：','成功取消该权限的分配');
                                                    }
                                                })
                                            }
                                        }
                                    }
                                })}
                }
            }
        });
    };

   //初始化tab页
    Role.prototype._initTab = function(){
        $('#role_tab').tabs({
            fit:true,
            border:false,
            plain:true
        });
    };

    /**
     * 事件绑定
     */
    Role.prototype._initEventBinding = function(){
        //【todo 在此编写绑定事件的方法。如按钮需要绑定的click事件。建议按如下格式绑定，并将this作为参数传入】
        this._$container.find('#role_add').on('click',{self:this},this._actions.openClick);
        this._$container.find('#role_delete').on('click',{self:this},this._actions.removeClick);
        this._$container.find('#role_save').on('click',{self:this},this._actions.roleSaveClick);
        this._$container.find('#role_userAdd').on('click',{self:this},this._actions.addUserClick);
        this._$container.find('#role_userDelete').on('click',{self:this},this._actions.removeUserClick);
    };
    /**
     * 在此定义此js用到的事件处理方法。如处理按钮click事件的方法
     */
    Role.prototype._actions = {

        //打开添加角色对话框
        openClick: function () {
            $('#role_group').form('clear');
            $('#roleDialog').dialog('open').dialog('center');
        },
        //删除角色
        removeClick:function (){
            var row = $('#role').datagrid('getSelected');
            if(row!=null){
                $.messager.confirm('确认', '确定要移除该角色吗?',function(r){
                if(r){
                    $.ajax({
                            type:'delete',
                            url:app.urlBuild("/dirms/security/role/"+row.id),
                            success:function(){
                                $('#role').datagrid('reload',{url:app.urlBuild("/dirms/security/role/all")});
                                $.messager.alert('提示：','删除成功');
                                $('#role_proerty').form('clear');
                            }
                        });
                    }
            });}
            else{ $.messager.alert('提示：','请选择要删除的角色');}
        },
        //保存相关信息
        roleSaveClick:function(evt) {
            var row = $('#role').datagrid('getSelected');
            //保存角色的基本属性
            if (row!=null) {
                var  roleDetail = app.utils.formToJSON(evt.data.self._$container.find("#role_property"));
                roleDetail.active = roleDetail.active === "on" ? true : false;
            $.ajax({
                url: evt.data.self.urlPaths.roleSave,
                type: "POST",
                cache: false,
                contentType: "application/json",
                dataType: "json",
                data: JSON.stringify(roleDetail),
                beforeSend:function(){
                    $.messager.progress({
                        title : '提示信息！',
                        text : '数据保存中，请稍后....'
                    });
                },
                success: function () {
                    $.messager.progress('close');
                    $.messager.alert('提示：', '保存成功');
                   // $('#role_property').form('clear');
                    $('#role').datagrid('reload');
                 },
                error:function(){alert("保存失败");$.messager.progress('close');}
             });
           }
            else{ $.messager.alert('提示：','请选择一个角色');}
        },

        //打开添加用户对话框
        addUserClick:function(){
            $('#user_nameId').textbox('clear');
            $('#user_name').textbox('clear');
            $('#addUserDialog').dialog('open').dialog('center').dialog('setTitle','添加用户');
        },
        //移除用户
        removeUserClick:function(){
            var row = $('#role_user').datagrid('getSelected');
            if(row!=null){
                $.messager.confirm('确认', '确定要移除该用户吗?',function(r){
                    if(r){
                        $.ajax({
                            type:'delete',
                            url:app.urlBuild("/dirms/security/user/"+row.id),
                            success:function(){
                                $('#role_user').datagrid('reload',{url:app.urlBuild("/dirms/security/user/all")});
                                $.messager.alert('提示：','删除成功')
                            }
                        });
                       }
                });
            }
            else{ $.messager.alert('提示：','请选择要删除的用户');}
        }
    };
    return Role;
});